/******************************************************************************************
 * Import
 ******************************************************************************************/

// module
import Taro, { Component } from '@tarojs/taro'
import { Picker, Radio, Input } from '@tarojs/components'

// project
import { CPage, CContent, CHeader, CFooter, CFloat, CAround, CBetween, CCenter, CRow, CWrap, CLine, CHand, CItemX, CItemY, CText, CLabel, CSvg, CImage, CButton, CColumn } from '../../library/comp';
import { Base64, Gen, Time, Zip, Session, Storage, Toast, Loading, Modal, ActionSheet } from '../../library/func';
import Icon from '../../project/style/icon';
import Http from '../../project/func/http/http'

/******************************************************************************************
 * Export Class
 ******************************************************************************************/

export default class Index extends Component {

	/*------------------------------------------------------------------------------------
	 * 初始化
	 *-----------------------------------------------------------------------------------*/
	constructor(props) {
		super(props);

		/**
		 * state
		 */
		this.state = {
			// 使用佣金选项
			selector:[
				'不使用佣金',
				'使用佣金'
			],
			selectorChecked:'不使用佣金',
			// 支付按钮
			button:'去支付',
			// 地址id
			takeid: 0,
			// 用户地址
			address:{},
			// 用户佣金
			commission: 0,
			// 要购买的商品
			list:[],
			// 总共件数
			allCount: 0,
			// 总共钱数
			allAmount: 0,
			// 实付金额
			payment: 0,
			// 提交数据
			// 用户备注
			mark:'',
			// 是否使用佣金支付
			is_commission: 0,
			// 支付方式
			enum_paytype: '微信支付',

		}
	}

	/*------------------------------------------------------------------------------------
	 * 生命周期
	 *-----------------------------------------------------------------------------------*/
	// willmount
	componentWillMount() {
		// let take = this.$router.params.takeid !=0 ? this.$router.params.takeid : this.state.takeid
		let take = this.$router.params.takeid ? Number(this.$router.params.takeid) : this.state.takeid

		this.setState({
			takeid: take
		})
	}
	// didMount
	componentDidMount() {
		// 判断takeid参数
		let data = {};
		if(typeof this.state.takeid == 'number'){
			data.takeid = this.state.takeid;
		}

		Http.get({
			url:'order/submit.php?takeid=' + this.state.takeid,
			data:data,
			success:(data) => {
				// 查看是否有地址，没有去添加
				if(data.take.length == 0){
					wx.navigateTo({
                        url: '/screen/user/address/list?type=1',
                    })
				}else{
					console.log(data)
					// 循环算总件数和总钱数
					let count = 0
					let amount = 0
					for(let v of data.list){
						count += v.count
						amount += parseFloat((parseFloat(v.set_price)*parseInt(v.count)).toFixed(2))
					}

					this.setState({
						address: data.take,
						commission: data.commission,
						list: data.list,
						allCount: count,
						allAmount: amount.toFixed(2),
						payment: amount.toFixed(2),
						takeid:data.take.id
					},()=>{
						let e={};
						e.detail={};
						e.detail.value = 1;
						this.didChange(e)
					})
				}
				
			}
		})
	}
	
	/*------------------------------------------------------------------------------------
	 * 事件处理
	 *-----------------------------------------------------------------------------------*/
	// onClick
	onClick = (id, e)=> {
		console.log('onClick: ' + id)
    }
    
    // onRedirect
    onRedirect = (url, e)=> {
        wx.redirectTo({
            url: url
        })
    }

    // onNavigate
    onNavigate = (url, e)=> {
		wx.navigateTo({
			url: url
		})
	}

	// 进页面是判断是否有佣金，有就使用佣金  didMount 调用
	didChange = e => {
		console.log('您的选择为：',this.state.selector[e.detail.value])
		this.setState({
		selectorChecked: this.state.selector[e.detail.value]
		})
		// 如果使用佣金
		if(e.detail.value == 1){
			// 佣金为0
			if(this.state.commission == 0){
				// 佣金为0,不能使用
				this.setState({
					selectorChecked: this.state.selector[0],
					is_commission: 0
				})
				return
			}else{
				// 佣金不为0
				// 如果佣金可以支付订单
				if(this.state.commission >= this.state.allAmount){
					this.setState({
						enum_paytype: '佣金全额支付',
						button: '佣金全额支付',
						payment: 0,
						is_commission: 1
					})
				}else{
					// 如果佣金不能全部支付订单
					this.setState({
						payment: allAmount - this.state.commission,
						is_commission: 1,
					})
				}
			}
		}
	}
	
	// 佣金使用
	onChange = e => {
		this.setState({
		  selectorChecked: this.state.selector[e.detail.value]
		})
		// 如果使用佣金
		if(e.detail.value == 1){
			// 佣金为0
			if(this.state.commission == 0){
				Toast.text('您的佣金为0,不能使用!')
				this.setState({
					selectorChecked: this.state.selector[0],
					is_commission: 0
				})
				return
			}else{
				// 佣金不为0
				// 如果佣金可以支付订单
				if(this.state.commission >= this.state.allAmount){
					this.setState({
						enum_paytype: '佣金全额支付',
						button: '佣金全额支付',
						payment: 0,
						is_commission: 1
					})
				}else{
					// 如果佣金不能全部支付订单
					this.setState({
						payment: (this.state.allAmount - this.state.commission).toFixed(2),
						is_commission: 1,
					})
				}
			}
		}
	  }

	//   用户留言
	onMark = (e)=> {
		console.log(e.detail.value)
		this.setState({
			mark: e.detail.value,
		})
	}

	//   订单提交
	onPay = ()=>{

		// 提交订单操作
		Http.post({
			url:'order/logic/submit.php',
			data:{
				mark: this.state.mark,
				is_commission: this.state.is_commission,
				enum_paytype: this.state.enum_paytype,
				// takeid: this.state.address.id
				takeid: this.state.takeid
			},
			success: (data) =>{
				// data.order_id 订单id
				// data.orderid 订单编号
				// total_fee 需要微信支付的金额，单位（分）
				// 取变量
				let orderid = data.orderid
				let total_fee = data.total_fee

				// 从localStorage 查询 openid
				wx.getStorage({
					key: 'openid',
					success(res) {
						let openid = res.data;
                        wx.request({
                            url: 'https://activepage.sgboke.com/pay/wepay/jsapi.php',
                            method: 'POST',
                            data: {
                                key: 'rushbuy',
                                orderid: orderid,
                                total_fee: total_fee,
                                openid: openid
                            },
                            header: {
                                'content-type': "application/x-www-form-urlencoded",
                            },
                            success(res) {

                                // 取参数
                                let nonceStr = res.data.nonceStr;
                                let prepay_id = res.data.package;
                                let paySign = res.data.paySign;
                                let timeStamp = res.data.timeStamp;

                                // 调起支付 
                                wx.requestPayment({
                                    timeStamp: timeStamp.toString(),
                                    nonceStr: nonceStr,
                                    package: prepay_id,
                                    signType: 'MD5',
                                    paySign: paySign,

                                    // 支付成功
                                    success: function(res) {
                                        console.log('成功');
                                        console.log(res);

                                        /**
                                         * 支付成功，调整订单状态，并跳转到未发货页面
                                         */
                                        Http.post({
                                            url: 'order/logic/ok.php',
                                            data: {
                                                orderid: orderid
                                            },

                                            // 调整订单状态成功
                                            success(res) {
                                                wx.redirectTo({
                                                    url: '/screen/user/order/list?status=未发货'
                                                });
                                            },
                                            code(err) {
                                                console.log('支付失败：调整订单状态，逻辑失败！');
                                                console.log(err);
                                            },
                                            server(err) {
                                                console.log('支付失败：调整订单状态，服务器失败！');
                                                console.log(err);
                                            },
                                            net(err) {
                                                console.log('支付失败：调整订单状态，网络失败！');
                                                console.log(err);
                                            }
                                        });
                                    },

                                    // 支付失败
                                    fail: function(err) {
                                        console.log('失败');
                                        console.log(err);
                                        /**
                                         * 支付失败，跳转到未支付页
                                         */
                                        wx.redirectTo({
                                            url: '/screen/user/order/list?status=未付款'
                                        });
                                    }
                                })
                                // console.log(res);
                            },
                            fail(err) {
                                console.log('支付失败：网络失败！');
                            }
                        })
					}
				})
			}

		})
	}

	/*------------------------------------------------------------------------------------
	 * 自定义方法
	 *-----------------------------------------------------------------------------------*/
	config = {
        navigationBarTitleText: '提交订单',
        navigationBarBackgroundColor: '#dd2f3c',
        navigationBarTextStyle: '#fff'
    }

	/*------------------------------------------------------------------------------------
	 * 渲染
	 *-----------------------------------------------------------------------------------*/
	render () {
		return (
			<CPage>
				<CContent mb='120'>
					
					{/* 地址部分 */}
					<CRow bg='#fff' my='20' mx='30' ra='16' px='20' py='30' onClick={this.onNavigate.bind(this, '/screen/user/address/list?type=1')}>
						<CItemY style='flex:2'>
							<CBetween>
								<CHand size='28'>
									<CSvg icon={Icon.location} w='34' h='34' color='#808080'></CSvg>
									<CHand ml='6'>收货人：{address.set_name}</CHand>
								</CHand>
								<CHand size='28'>{address.set_mobile}</CHand>
							</CBetween>
							<CHand size='28' mt='18' color='#7a7a7a'>收货地址：{address.set_address}</CHand>
						</CItemY>
						<CSvg icon={Icon.right} w='30' h='30' ml='20' color='#a1a1a1'></CSvg>
					</CRow>

					{/* 余额 */}
					<CRow bg='#fff' my='20' mx='30' pa='20' ra='16'>
						<CBetween>
							<CLine>
								<CHand size='28' color='#707070'>可使用佣金</CHand>
								<CHand size='28' color='#c9322c' ml='6'>￥{commission}</CHand>
							</CLine>
							<CLine x='right'>
								<Picker mode='selector' range={this.state.selector} onChange={this.onChange}>
									<CRow y='center'>
										<CHand size='28' color='#707070'>{this.state.selectorChecked}</CHand>
										<CSvg icon={Icon.down} w='30' h='30' ml='10' color='#a1a1a1'></CSvg>
									</CRow>
								</Picker>
							</CLine>
						</CBetween>
					</CRow>

					{/* 微信支付 */}
					<CRow bg='#fff' my='20' mx='30' pa='20' ra='16'>
						<CBetween>
							<CLine>
								<CSvg icon={Icon["wechat-3"]} w='40' h='40' color='#3da92f'></CSvg>
								<CText size='28' pl='10'>微信支付</CText>
							</CLine>
							<CLine x='right'>
								<CSvg icon={Icon.fit} color='#c9322c' w='40' h='40'></CSvg>
								{/* <Radio checked color='#c9322c'></Radio> */}
							</CLine>
						</CBetween>
					</CRow>

					{/* 具体商品 */}
					<CRow bg='#fff' my='20' mx='30' ra='16'>
						<CColumn>
							<CLine bb='1 solid #f8f8f8' pa='20'>
								<CSvg icon={Icon.store} w='35' h='33' color='#777'></CSvg>
								<CText size='28' pl='16'>每日一达</CText>
							</CLine>
							{this.state.list.map(item => {
								return (
									<CLine pa='20' y='center' bb='1 solid #f8f8f8'>
										<CImage src='http://image.cdn.hesq.com.cn/rushbuy/product/{{item.product_object.set_image_small}}' w='140' h='140'/>
										<CColumn pl='20'>
											<CLine >
												<CText size='28' color='#252525'>{item.set_name}</CText>
											</CLine>
											<CBetween pt='20'>
												<CText size='28' pr='20'  color='#d45f58'>￥{item.set_price}</CText>
												<CText size='24' color='#aaa'>x{item.count}</CText>
											</CBetween>
										</CColumn>
									</CLine>
								)
							})}
							<CLine bg='#f6f6f6' my='20' mx='30' px='10' py='4'>
								<CSvg icon={Icon.msg} w='36' h='36' color='#cbcbcb'></CSvg>
								<Input type='text' placeholder='给卖家留言' class='w1' value={this.state.mark} onInput={this.onMark} placeholderStyle='font-size:28rpx;' style='padding-left:16rpx; font-size:28rpx;'/>
							</CLine>
							<CRow mx='30'>
								<CColumn>
									<CAround mt='20'>
										<CLine size='27' x='left' color='#626262'>共{allCount}件商品</CLine>
										<CLine size='27' x='right' color='#626262'>商品金额：</CLine>
										<CLine size='27' x='right' color='#626262'>{allAmount}</CLine>
									</CAround>
									<CAround mt='20'>
										<CLine size='27' x='left'></CLine>
										<CLine size='27' x='right' color='#626262'>运费：</CLine>
										<CLine size='27' x='right' color='#d76861'>+ 0.00</CLine>
									</CAround>
									<CAround my='20'>
										<CLine size='27' x='left'></CLine>
										<CLine size='27' x='right' color='#d76861'>小计：</CLine>
										<CLine size='27' x='right' color='#d76861'>{allAmount}</CLine>
									</CAround>
								</CColumn>
							</CRow>
						</CColumn>
					</CRow>

				</CContent>

				{/* 底部 */}
				<CFooter h='98' bg='#fff' y='center' bt='1 solid #e3e3e3'>
					<CBetween>
						<CLine pl='30'>
							<CHand size='28'>实付款:</CHand>
							<CHand color='#c9322c' size='36' bold>￥{payment}</CHand>
						</CLine>
						<CLine x='right'>
							<CButton style='font-size:28rpx;' bg='#c9322c' color='#fff' h='100' lh='100' px='60' onClick={this.onPay}>{this.state.button}</CButton>
						</CLine>
					</CBetween>
				</CFooter>
			</CPage>
		)
	}
}


